/*
 * Copyright 2015 www.hyberbin.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * Email:hyberbin@qq.com
 */
package com.wulis.common.utils;




import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.*;
import java.util.Optional;

/**
 * @author wuligao
 * @date 日期：2024年02月04日
 * @description : 反射工具类
 */
@Slf4j
public class ReflectionUtil {

    private ReflectionUtil() {
    }


    /**
     * 执行反射执行
     *
     * @param className 类型
     * @return 类的实例
     */
    @SuppressWarnings("rawtypes")
    public static Object instance(String className) {
        try {
            Class dialectCls = Class.forName(className);
            return dialectCls.newInstance();
        } catch (ClassNotFoundException e) {
            log.error(ReflectionUtil.class.getName() + "[无法找到方言类]", e);
            return null;
        } catch (InstantiationException | IllegalAccessException e) {
            log.error(ReflectionUtil.class.getName() + "[实例化方言错误]", e);
            return null;
        }
    }


    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     * @param obj 源对象
     * @param fieldName 属性名称
     * @param value 值
     */
    public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
        Optional<Field> optional = getAccessibleField(obj, fieldName);
        if (!optional.isPresent()) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
        }
        Field field = optional.get();
        try {
            field.set(obj, value);
        }  catch (IllegalAccessException ex) {
            throw new RuntimeException("方法访问失败");
        }
    }



    /**
     * 循环向上转型，获取对象的DeclaredField，并强制设置为可访问。
     * <p>
     * 如果向上转型到Object类仍无法找到该字段，返回Optional.empty()。
     * </p>
     *
     * @param targetObject 待获取字段的对象
     * @param targetFieldName 要获取的字段名
     * @return Optional包含可访问的Field对象，如果找不到则返回Optional.empty()
     */
    public static Optional<Field> getAccessibleField(final Object targetObject, final String targetFieldName) {
        for (Class<?> superClass = targetObject instanceof Class ? (Class<?>) targetObject : targetObject.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(targetFieldName);
                field.setAccessible(true);
                return Optional.of(field);
            } catch (NoSuchFieldException e) {
                // Field不在当前类定义，继续向上转型
            }
        }
        return Optional.empty();
    }


    /**
     * 构建实体的getter方法
     *
     * @param name 成员变量名
     * @return 方法名字
     */
    public static String get(String name) {
        //get+变量名的第一个字母大写
        return "get" + (name.charAt(0) + "").toUpperCase() + name.substring(1);
    }

    /**
     * 构建实体的setter方法名字
     *
     * @param name 成员变量名
     * @return 方法名字
     */
    public static String set(String name) {
        //get+变量名的第一个字母大写
        return "set" + (name.charAt(0) + "").toUpperCase() + name.substring(1);
    }
}
